//
//  SearchAndResultListViewController.m
//  YaoHeAPP
//
//  Created by 杨亚森 on 16/7/26.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "SearchAndResultListViewController.h"
#import "Masonry.h"
#import "MJExtension.h"
#import "CustomSearchView.h"
#import "Controller.h"
#import "SouSuoTiaoJianResultModel.h"
#import "Controller.h"
#import "SVPullToRefresh.h"
#import "labelview.h"
#import "TongYong.h"
#import "SearchResultCell.h"
#import "SearchAndResulModel.h"
#import "SearchListItemModel.h"
#import "AccurateVC.h"
#import "JiaGeZouShiDetailListModel.h"
#import "JiaGeZouShiItemModel.h"
#import "NSDate+DateFormatter.h"
#import "ChartView.h"

#define kSearchResultCell @"SearchResultCell"

@interface SearchAndResultListViewController () <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate> {
    NSMutableArray *_arrayList;//报价数组；
    labelview *_la;//无数据显示的页面
    UILabel *_neirongLable;
    NSMutableDictionary *_shaixuanDic;
}

@property (nonatomic, strong) UITableView *tableview;  //定义大表格
@property (nonatomic, assign) NSInteger  page;//页数
@property (nonatomic, strong) UIView *backView;//底部的视图
@property (nonatomic, strong) SearchAndResulModel *searchAndResulModel;
@property (nonatomic, strong) CustomSearchView *customSearchView;                                                               // 自定义搜索View
@property (nonatomic, strong) UIButton *shaixuanButton;                                                                         // 筛选按钮
@property (nonatomic, strong) ChartView *chartView;                                                                             // 曲线图
@property (nonatomic, strong) NSMutableArray *xZhouPointArray;                                                                 // 曲线图的数据源
@property (nonatomic, strong) NSMutableArray *xyPointArray;                                                                    // 曲线图的数据源
@property (nonatomic, strong) UIView *mengbanView;                                                                             // 蒙版View
@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;                                                  // 全局变量

@end

@implementation SearchAndResultListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden=YES;
    
    self.view.backgroundColor = bgVCcolor;
    //加一个导航条
    UIView *navcBar = [[UIView alloc] init];
    navcBar.backgroundColor = [UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(60);  make.right.offset(0);
    }];
    
    //导航条标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"市场价格查询";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(30);
        make.height.offset(28);
        make.bottom.offset(-6);
    }];
    
    // 筛选按钮
    UIButton *shaixuanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shaixuanButton setTitle:@"筛选" forState:UIControlStateNormal];
    [shaixuanButton addTarget:self action:@selector(shaiXuanButtonOnClick) forControlEvents:UIControlEventTouchUpInside];
    shaixuanButton.hidden = YES;
    [navcBar addSubview:shaixuanButton];
    [shaixuanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-15);
        make.width.offset(50);
        make.height.offset(40);
        make.bottom.offset(0);
    }];
    self.shaixuanButton = shaixuanButton;
    
    _arrayList = [[NSMutableArray alloc] init];
    
    //创建表格
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 65, self.view.frame.size.width, SCREEN_HEIGHT-65) style:UITableViewStylePlain];
    _tableview.backgroundColor = RGBCOLOR(230, 232, 241);
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = NO;
    [self.view addSubview:_tableview];
    
    _backView = [[UIView alloc] init];
    _backView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _backView.hidden = YES;
    [self.view addSubview:_backView];
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.right.offset(0);
        make.bottom.offset(0);
        make.height.offset(60);
    }];
    
    //电话找货按钮
    UIButton *phoneBtnz = [UIButton buttonWithType:UIButtonTypeCustom];
    phoneBtnz.layer.masksToBounds = YES;
    phoneBtnz.layer.cornerRadius = 18;
    [phoneBtnz setBackgroundImage:[UIImage imageNamed:@"Phone_call_for_goods"] forState:UIControlStateNormal];
    [phoneBtnz setBackgroundImage:[UIImage imageNamed:@"phoneFindHF"] forState:UIControlStateHighlighted];
    [phoneBtnz addTarget:self action:@selector(callPhone) forControlEvents:UIControlEventTouchUpInside];
    [_backView addSubview:phoneBtnz];
    [phoneBtnz mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.height.offset(40);
        make.width.offset(40);
        make.bottom.offset(-10);
    }];

    //重新采购
    UIButton *shaixuan_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    shaixuan_Btn.layer.masksToBounds = YES;
    shaixuan_Btn.layer.cornerRadius = 20;
    shaixuan_Btn.backgroundColor = [UIColor colorWithRed:55.f/255.f green:177.f/255.f blue:249.f/255.f alpha:1];
    [shaixuan_Btn addTarget:self action:@selector(shaiXuanButtonOnClick) forControlEvents:UIControlEventTouchUpInside];
    [shaixuan_Btn setTitle:@"重新筛选" forState:UIControlStateNormal];
    [shaixuan_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_backView addSubview:shaixuan_Btn];
    [shaixuan_Btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneBtnz.mas_right).offset(10);
        make.right.offset(-20);
        make.height.offset(36);
        make.bottom.offset(-12);
    }];

    //放置下拉上拉刷新控件
    __weak SearchAndResultListViewController *weakSelf = self;
    
    // setup pull-to-refresh
    [self.tableview addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
    
    // setup infinite scrolling
    [self.tableview addInfiniteScrollingWithActionHandler:^{
        [weakSelf insertRowAtBottom];
    }];
    
    // 获取查询条件数据
    [self loadShaiXuanResultData];
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeTa)];
    gesture.delegate = self;
    gesture.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:gesture];
    self.tapGestureRecognizer = gesture;

}
- (void)insertRowAtTop {
    //传属性值
    __weak SearchAndResultListViewController *weakSelf = self;
    
    [weakSelf.tableview beginUpdates];
    
    _page=1;
    NSNumber*number1 = [NSNumber numberWithInteger:1];
    NSNumber*number2 = [NSNumber numberWithInteger:10];
    NSMutableDictionary *di = [NSMutableDictionary dictionaryWithDictionary:_shaixuanDic];
    [di setValue:number1 forKey:@"page_num"];//分页,页码
    [di setValue:number2 forKey:@"page_step"];//page_step
    
    [Controller requestWithURL:QueryPriceList jsondic:di finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            [_arrayList removeAllObjects];
            
            _searchAndResulModel = [SearchAndResulModel mj_objectWithKeyValues:data.data];
            
            [_arrayList addObjectsFromArray:_searchAndResulModel.PriceList];
            
            //判断 是否  有 无数据
            if (_arrayList.count==0) {
                if (_la) {
                    [_la removeFromSuperview];
                }
                _la = [[labelview alloc]init];
                NSString *tishimessage = [NSString stringWithFormat:@"抱歉！系统没有收录“%@ %@/%@ %@”的价格",_shaixuanDic[@"TypeName"],_shaixuanDic[@"MaterialName"],_shaixuanDic[@"SurfaceName"],_shaixuanDic[@"WidthName"]];
                [_la setimage:@"cry" tit:tishimessage buttontit:nil frem:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
                _la.backgroundColor = [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
                _la.image.frame = CGRectMake((self.view.frame.size.width-150)/2, 100, 150, 157);
                _la.label.frame = CGRectMake(30, 260, self.view.frame.size.width-60, 30);
                [_tableview addSubview:_la];
    
                _backView.hidden=NO;
            } else {
                if (_la) {
                    [_la removeFromSuperview];
                }
                _backView.hidden = YES;
                _tableview.frame = CGRectMake(0,100, self.view.frame.size.width, SCREEN_HEIGHT-100);
                
                if (_neirongLable) {
                    [_neirongLable removeFromSuperview];
                }
                
                _neirongLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 67.5, SCREEN_WIDTH-20, 30)];
                _neirongLable.textAlignment=NSTextAlignmentLeft;
                _neirongLable.font = [UIFont systemFontOfSize:13];
                NSString *neirongmessage = [NSString stringWithFormat:@"搜索内容：%@ %@/%@ %@",_shaixuanDic[@"TypeName"],_shaixuanDic[@"MaterialName"],_shaixuanDic[@"SurfaceName"],_shaixuanDic[@"WidthName"]];
                _neirongLable.text = neirongmessage;
                _neirongLable.textColor = RGBCOLOR(153, 153, 153);
                [self.view addSubview:_neirongLable];
                
                [self.tableview reloadData];
            }
        } else {
            
        }
    }];
    
    // 3. 结束刷新(相当于动画)
    [weakSelf.tableview endUpdates];
    
    [weakSelf.tableview.pullToRefreshView stopAnimating];
}
- (void)insertRowAtBottom {
    
    __weak SearchAndResultListViewController *weakSelf = self;
    
    [weakSelf.tableview beginUpdates];
    
    _page = _page + 1;
    NSNumber*number1 = [NSNumber numberWithInteger:_page];
    NSNumber*number2 = [NSNumber numberWithInteger:10];
    NSMutableDictionary *di = [NSMutableDictionary dictionaryWithDictionary:_shaixuanDic];
    [di setValue:number1 forKey:@"page_num"];//分页,页码
    [di setValue:number2 forKey:@"page_step"];//page_step
    
    [Controller requestWithURL:QueryPriceList jsondic:di finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]]) {
            _searchAndResulModel = [SearchAndResulModel mj_objectWithKeyValues:data.data];
            [_arrayList addObjectsFromArray:_searchAndResulModel.PriceList];
            
            [self.tableview reloadData];
        } else {
            
        }
    }];
    
    [weakSelf.tableview endUpdates];
    [weakSelf.tableview.infiniteScrollingView stopAnimating];
}

- (void)shaiXuanButtonOnClick {
    if (_mengbanView != nil) {
        [self closeTa];
    }
    [self.view addSubview:self.customSearchView];
    [self.customSearchView bringToFront];
    self.shaixuanButton.hidden = YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _arrayList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:kSearchResultCell];
    if (!cell) {
        cell = [[SearchResultCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kSearchResultCell];
    }
    SearchListItemModel *searchListItemModel = _arrayList[indexPath.row];
    cell.searchListItemModel = searchListItemModel;
    
    cell.searchResultCellImageBtnActionBlock = ^(SearchListItemModel *searchListItemModel) {
        [self load7daysOfPricesData:searchListItemModel];
    };

    cell.searchResultCellNeedBtnActionBlock = ^() {
        if (_mengbanView != nil) {
            [self closeTa];
        }
        
        AccurateVC *accurate = [[AccurateVC alloc] init];
        accurate.searchListItemModel = searchListItemModel;
        accurate.typeString = _shaixuanDic[@"TypeName"];//传过去字符串（判断该以什么样的方式显示）
        accurate.pageString = @"我要买";
        [self.navigationController pushViewController:accurate animated:YES];
    };

    return cell;
}

//拨打客服电话
- (void)callPhone {
    //进入打电话页面
    UIWebView *webview = [[UIWebView alloc] init];
    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel:4008850051"]]];
    [self.view addSubview:webview];
}

- (void)backLogin {
    if (_mengbanView != nil) {
        [self closeTa];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 请求筛选数据
- (void)loadShaiXuanResultData {
    [Controller requestWithURL:HuoQuJiaGeChaXunTiaoJian jsondic:nil finishBlock:^(ClassData* data) {
        if (data.number.intValue == 0) {
            self.customSearchView.souSuoTiaoJianResultModel = [SouSuoTiaoJianResultModel mj_objectWithKeyValues:data.data];
            [self.view addSubview:self.customSearchView];
        }
    }];
}

#pragma mark 请求曲线图数据
- (void)load7daysOfPricesData:(SearchListItemModel *)searchListItemModel {
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    [paramDict setObject:searchListItemModel.SheetCoilSettingCode forKey:@"SheetCoilSettingCode"];
    [paramDict setObject:searchListItemModel.ThinkCode forKey:@"ThinkCode"];
    [paramDict setObject:@7 forKey:@"Top"];
    [paramDict setObject:searchListItemModel.IsAm forKey:@"IsAm"];
    [Controller requestWithURL:Query7DaysPriceDetail jsondic:paramDict finishBlock:^(ClassData* data) {
        if (data.number.intValue == 0) {
            NSMutableArray *xZhouPointArray = [NSMutableArray array];
            NSMutableArray *xyPointArray = [NSMutableArray array];
            JiaGeZouShiDetailListModel *jiaGeZouShiDetailListModel = [JiaGeZouShiDetailListModel mj_objectWithKeyValues:data.data];
            NSArray *jiaGeZouShiDetailListArray = jiaGeZouShiDetailListModel.Detail;
            
            for (int i = (int)jiaGeZouShiDetailListArray.count-1; i >= 0 ; i--) {
                JiaGeZouShiItemModel *jiaGeZouShiItemModel = jiaGeZouShiDetailListArray[i];
                [xZhouPointArray addObject:[self toolMethodUseOnce:jiaGeZouShiItemModel.PriceDate]];
                [xyPointArray addObject:jiaGeZouShiItemModel.Price];
            }
            
            self.xZhouPointArray = xZhouPointArray;
            self.xyPointArray = xyPointArray;
            
            [self.mengbanView addSubview:self.chartView];
        }
    }];
}

#pragma mark TooL Method
- (NSString *)toolMethodUseOnce:(NSString *)priceDateString {
    NSRange zuokuohaoRange = [priceDateString rangeOfString:@"("];
    NSRange youkuohaoRange = [priceDateString rangeOfString:@")"];
    NSString *shijianchuo = [priceDateString substringWithRange:NSMakeRange(zuokuohaoRange.location+1, youkuohaoRange.location - zuokuohaoRange.location-1)];
    long tempLong = [shijianchuo longLongValue];
    NSDate *thisDate = [NSDate dateWithTimeIntervalSince1970:tempLong/1000];
    
    return [NSDate formatDate:thisDate WithDateFormat:@"MM-dd"];
}

#pragma mark - lazy load
- (CustomSearchView *)customSearchView {
    if (!_customSearchView) {
        _customSearchView = [[CustomSearchView alloc] initWithFrame:CGRectMake(0, 60, self.view.width, self.view.height-60)];
    }
    __block SearchAndResultListViewController *weakSelf = self;
    _customSearchView.customSearchViewCancelOrConformBlock = ^(NSMutableDictionary *blockDictionary) {
        [weakSelf closeIt];
        if (blockDictionary) {
            // 点击确认按钮操作
            //先保存 传过来的字典
            _shaixuanDic = [NSMutableDictionary dictionaryWithDictionary:blockDictionary];
            //刷新数据
            [weakSelf insertRowAtTop];
        }
    };
    return _customSearchView;
}

- (void)closeIt {
    [self.customSearchView removeFromSuperview];
    self.shaixuanButton.hidden = NO;
}

- (ChartView *)chartView{
    if (!_chartView) {
        _chartView = [[ChartView alloc] initWithFrame:CGRectMake(0, 30, self.view.width, 220)];
    }
    _chartView.arrayX = self.xZhouPointArray;
    _chartView.arrayY = self.xyPointArray;
    [_chartView setData];
    
    return _chartView;
}

- (UIView *)mengbanView {
    if (!_mengbanView) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        _mengbanView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2-110, self.view.width, 250)];
        _mengbanView.backgroundColor = [UIColor colorWithWhite:0.05f alpha:0.6f];// 此行代码牛逼,解决了下面View透明,上面View不透明的问题
        _mengbanView.userInteractionEnabled = YES;
        [window addSubview:_mengbanView];
        
        UILabel *sevenDayTipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, self.view.width, 30)];
        sevenDayTipLabel.text = @"市场近7天报价";
        sevenDayTipLabel.textColor = [UIColor whiteColor];
        sevenDayTipLabel.textAlignment = NSTextAlignmentCenter;
        sevenDayTipLabel.font = Font(14);
        [_mengbanView addSubview:sevenDayTipLabel];
        
        UIImageView *guanbiImageView = [[UIImageView alloc] init];
        guanbiImageView.image = [UIImage imageNamed:@"ic_close_imageviewer"];
        guanbiImageView.frame = CGRectMake(self.view.width-35, 10, 25, 25);
        [guanbiImageView addTapAction:@selector(closeTa) target:self];
        [_mengbanView addSubview:guanbiImageView];
    }
    
    return _mengbanView;
}

- (void)closeTa {
    if (_mengbanView) {
        [_chartView removeFromSuperview];
        [_mengbanView removeFromSuperview];
        _mengbanView = nil;
    }
}

@end
